package com.cb.msmservice.controller;

import com.cb.msmservice.service.MsmService;
import com.cb.msmservice.utils.RandomUtil;
import com.cb.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author cb
 * @version 1.0
 * @date 2020/6/27 11:03
 */
@Api(description = "阿里云msm管理")

@RestController
@RequestMapping("/msmservice/msm")
public class MsmController {

    private final MsmService msmService;

    @Autowired
    public MsmController(MsmService msmService) {
        this.msmService = msmService;
    }

    @ApiOperation("获取手机号发送短信验证码")
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
        // 1.尝试从redis获取验证码
        String code = msmService.getCodeFromRedis(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.ok();
        }

        // 2.redis没有验证码, 则自行生成, 由阿里云发送
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>(2);
        param.put("code", code);
        boolean isSend = msmService.send(param, phone);
        if (!isSend) {
            return R.error().message("短信发送失败");
        }
        // 3.发送成功, 设置到redis中
        msmService.setCodeToRedis(phone, code, 5, TimeUnit.MINUTES);

        return R.ok();
    }

}

